import { GlobalFunction } from "../base/GlobalFunction";
import { GlobalEvent } from "../base/GlobalEvent";
import { ConstData } from "../base/ConstData";
import { ifPosition } from "../Data/dataBase";
import { netService } from "../netServices/netServices";

const { ccclass, property } = cc._decorator;

@ccclass
export default class movePlayer extends cc.Component {

    @property(cc.Animation)
    aniCharacter: cc.Animation = null;
    @property(cc.Node)
    modelBody: cc.Node = null;

    body: cc.RigidBody;

    private moveDir: cc.Vec2 = cc.v2(0, 0);
    private PlayingDir: number;

    onLoad() {
        this.body = this.getComponent(cc.RigidBody);

        GlobalEvent.on(GlobalEvent.Event.joyStickDir, function(Event){
            this.moveDir = Event.Dir;
        }.bind(this), this);

        GlobalEvent.on(GlobalEvent.Event.joyStickStop, function(Event){
            this.moveDir = null;
        }.bind(this), this);
    }

    getDirection(dirv) {
        let radian = cc.misc.degreesToRadians(-22.5);    // 将角度转换为弧度
        let comVec = cc.v2(0, -1);    // 一个水平向上的对比向量
        comVec = comVec.rotate(-radian);    // 将对比向量旋转给定的弧度返回一个新的向量
        let degree = GlobalFunction.getVecDegree(dirv, comVec);
        if (degree < 0) degree += 360;
        return Math.floor(degree / 45);
    }

    playCharacterAni(dir) {
        if (this.PlayingDir != dir) {
            var state = this.aniCharacter.play(ConstData.dirConfig[dir].clip_name);
            state.repeatCount = Infinity;
            this.PlayingDir = dir;
        }
    }

    walk(dirvec: cc.Vec2) {
        var _veclocity = cc.v2(0,0);
        dirvec.scale(cc.v2(250,250),_veclocity)
        this.body.linearVelocity = _veclocity;
        this.playCharacterAni(this.getDirection(dirvec))
    }

    update(dt) {
        if (!this.moveDir) return;
        if (this.modelBody) {
            this.modelBody.getComponent("modelBase").setDirection(GlobalFunction.getDirection(this.moveDir));
        }
        this.walk(this.moveDir);

        var position:ifPosition = {
            x:this.node.position.x,
            y:this.node.position.y,
        }
        netService.Ins().updatePosition(position);
    }
}


